package example.documentbased.mainModule.services.mocks
{
	import example.documentbased.mainModule.models.doman.Editor;
	import example.documentbased.mainModule.models.factories.ItemsFactory;
	import example.documentbased.mainModule.services.IEditorService;
	
	import mx.utils.UIDUtil;
	
	import raix.reactive.IObservable;
	import raix.reactive.Observable;
	import raix.reactive.Unit;
	
	public class EditorServiceMock implements IEditorService
	{
		private var _model:ServiceMockModel;
		private var _itemsFactory:ItemsFactory;
		
		public function EditorServiceMock(model:ServiceMockModel, itemsFactory:ItemsFactory)
		{
			_model = model;
			_itemsFactory = itemsFactory
		}
		
		public function getEditors():IObservable
		{
			return Observable.defer(function():IObservable 
			{
				return Observable.value(_model.editors);
			}).delay(500);
		}
		
		public function getEditor(id:String):IObservable
		{
			var editr:Editor = getEditorById(id);
			trace("get editor color", editr.color);
			
			return Observable.defer(function():IObservable 
			{
				return Observable.value(editr);
			}).delay(500);
		}
		
		public function saveEditor(editor:Editor):IObservable
		{
			var editr:Editor;
			var id:String;
			
			if (editor.id)
			{
				id = editor.id;
				editr = getEditorById(editor.id);
				// if editr == null should handle exception here
				editr.id = editor.id;
				editr.name = editor.name;
				editr.color = editor.color;
				trace("save editor color", editor.color);
			}
			else
			{
				id = UIDUtil.createUID();
				editr = _itemsFactory.createEditor(id, editor.name, editor.color);
				_model.editors.push(editr);
			}
			
			return Observable.defer(function():IObservable 
			{
				return Observable.value(id);
			}).delay(500);
		}
		
		public function removeEditor(editor:Editor):IObservable
		{
			if (editor.id)
			{
				var editr:Editor = getEditorById(editor.id);
				_model.editors.splice(_model.editors.indexOf(editr), 1);
			}
			return Observable.defer(function():IObservable 
			{
				return Observable.value(new Unit());
			}).delay(500);
		}
		
		private function getEditorById(id:String):Editor
		{
			for (var i:int = 0; i < _model.editors.length; i++) 
			{
				if (_model.editors[i].id == id)
				{
					return _model.editors[i];
				}
			}
			return null;
		}
	}
}